<?php

namespace App\Traits;

use App\Models\ProductCate;

trait ModelTrait
{
    /**
     * @param array $where
     * @param string $orderName
     * @param string $order
     * @param int $page
     * @return mixed
     */
    public static function paginateList($where = [], $orderName = 'created_at', $order = 'DESC', $page = 15)
    {
        $where = collect($where);

        // 是否正倒序排列
        if ($where->has('sort_order')) {
            $orderName = 'sort_order';
            $order = $where->get('sort_order');
        }

        $query = static::with(['cate', 'sku']);

        // 根据标题检索
        if ($title = $where->get('title')) {
            $query->where('title', 'like', "%{$title}%");
        }

        // 根据状态筛选
        if (!is_null($where->get('flag'))) {
            $query->where('flag', $where->get('flag'));
        }

        if (!is_null($where->get('recommend'))) {
            $query->where('recommend', $where->get('recommend'));
        }

        // 根据分类检索
        if ($cateId = $where->get('cate_id')) {
            // 获取所有子分类id(包含自己)
            $ids   = ProductCate::descendantsAndSelf($cateId)->pluck('id');
            $query->whereIn('cate_id', $ids);
        }

        if ($limit = $where->get('limit')) {
            $page = $limit;
        }

        return $query->orderBy($orderName, $order)->latest('id')->paginate($page);
    }
}
